<?php

namespace App\Http\Controllers\BG;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Input;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Config;

use Illuminate\Support\Facades\DB;
use Cache;
use Validator;
use Carbon\Carbon;

use \GatewayWorker\Lib\Gateway;

use  App\Models\Weixin;
use  App\Models\WeixinFriendList;
use  App\Models\ChatMessage;
use App\Models\Phone;
use App\Models\WeixinGroup;
use App\Models\PhoneCopy;
use  App\Models\User;

class WeixinController extends Controller
{
    public function list(Request $request)
    {
        $input = Input::only('page', 'limit','str','weixin_status','group_id');
        $validator = Validator::make($input, [        
            'page'      => 'required',
            'limit'         => 'required',
            'str'     =>  'nullable',
            'weixin_status'     =>  'nullable',
            'group_id'     =>  'nullable',
        ]);
        if ($validator->fails()) {
            return $this->returnError([],401,'参数错误');
        }
        $weixin = Weixin::where('id','>',0);
        $page = $input['page'];
        $limit = $input['limit'];
        if(isset($input['str'])){
            
        }
        // if(isset($input['phone_status'])){
        //     if($input['phone_status'] == 'on'){
        //         $weixin->where('client_id','>',0); 
        //     }else{
        //         $weixin->where('client_id','=',''); 
        //     }
        // }
        if(isset($input['group_id'])){
            $weixin->where('group_id',$input['group_id']); 
        }
        if(isset($input['weixin_status'])){
            if($input['weixin_status']=='off'){
                $weixin->where('phone_client_id',0); 
            }else{
                $weixin->where('phone_client_id','>',0); 
            }
        }
        $count = $weixin->count();
        $data =  $weixin->offset(($page-1)*$limit)
            ->limit($limit)->get();
        $data = $this->calcData($data);
        $fin['count'] = $count;
        $fin['data'] = $data;
        return $this->returnOk($fin);
    }

    protected function calcData($data)
    {
        foreach ($data as $key => $value) {
            $data[$key]['friend_man'] = WeixinFriendList::where('weixin_uid',$value['uid'])->where('sex','1')->count();
            $data[$key]['friend_women'] = WeixinFriendList::where('weixin_uid',$value['uid'])->where('sex','2')->count();
            $data[$key]['friend_all'] = WeixinFriendList::where('weixin_uid',$value['uid'])->count();
            $data[$key]['chat_yesterday'] = ChatMessage::where('uid',$value['uid'])->where('created_at','>',Carbon::yesterday())->where('created_at','<',Carbon::today())->count();
            $week = Carbon::now()->subDay(7)->toDateTimeString();
            $month = Carbon::now()->subDay(30)->toDateTimeString();
            $data[$key]['chat_week'] = ChatMessage::where('uid',$value['uid'])->where('created_at','>',$week)->count();
            $data[$key]['chat_month'] = ChatMessage::where('uid',$value['uid'])->where('created_at','>',$month)->count();
            $phone = Phone::where('wechat_uid',$value['uid'])->first();
            $data[$key]['phone_imei'] = '';
            $data[$key]['phone_remark'] = '';
            $data[$key]['phone_user_name'] = '';
            $data[$key]['phone_status'] = 'off';
            $data[$key]['user_status'] = 'off';
            $data[$key]['weixin_status'] = 'off';
            $data[$key]['group_name'] = '';
            $group = WeixinGroup::get();
            if($value['group_id']){
                foreach ($group as $k => $val) {
                    if($val['id'] == $value['group_id']){
                        $data[$key]['group_name'] = $val['name'];
                    }
                }
            }
            if($phone){
                $data[$key]['phone_imei'] = $phone['imei'];
                $data[$key]['phone_remark'] = $phone['remark'];
                if($phone['user_id']){
                    $user = User::where('id',$phone['user_id'])->first();
                    if($user['client_id']&&Gateway::isOnline($user['client_id'])){
                        $data[$key]['user_status'] = 'on';
                    }
                    $data[$key]['phone_user_name'] = $user['name']??'';
                }
                if($phone['client_id']&&Gateway::isOnline($phone['client_id'])){
                    $data[$key]['phone_status'] = 'on';
                }
            }
            if($value['phone_client_id']&&Gateway::isOnline($phone['client_id'])){
                $data[$key]['weixin_status'] = 'on';
            }else{
                $t = Weixin::where('id',$value['id'])->first();
                $t->phone_client_id = '';
                $t->save();
            }
        }
        return $data;
    }

    public function setGroup(Request $request)
    {
        $input = Input::only('id', 'group_id');
        $validator = Validator::make($input, [        
            'id'      => 'required|integer',
            'group_id'         => 'required',
        ]);
        if ($validator->fails()) {
            return $this->returnError([],401,'参数错误');
        }
        $weixin = Weixin::where('id',$input['id'])->select('id','remark','group_id')->first();
        if($weixin){
            $weixin->group_id = $input['group_id'];
            $weixin->save();
            return $this->returnOk();
        }else{
            return $this->returnError([],409,'微信不存在');
        }
    }

    public function setRemark(Request $request)
    {
        $input = Input::only('id', 'remark');
        $validator = Validator::make($input, [        
            'id'      => 'required|integer',
            'remark'         => 'nullable',
        ]);
        if ($validator->fails()) {
            return $this->returnError([],401,'参数错误');
        }
        $weixin = Weixin::where('id',$input['id'])->select('id','remark','group_id')->first();
        if($weixin){
            $weixin->remark = $input['remark']??'';
            $weixin->save();
            return $this->returnOk();
        }else{
            return $this->returnError([],409,'微信不存在');
        }
    }

    public function delete()
    {
        $input = Input::only('id');
        $validator = Validator::make($input, [   
            'id'      => 'required',
        ]);
        if ($validator->fails()) {
            return $this->returnError([],401,'参数错误');
        }
       
        $where['id'] = $input['id'];
        $exist = Weixin::where($where)->first();
        if($exist){
            $exist->delete();
        }else{
            return $this->returnError([],409,'微信不存在');
        }
        return $this->returnOk();
    }

    public function send_msg()
    {
        // $client = PhoneCopy::where('imei','{"data":{"imei":"352531082766203","userName":"ljkj7442"},"type":"CONNECT_WITH_WEIXIN"}')->orderBy('id', 'desc')->first();
        // $client_id = $client['version'];
        $new_message = array(
            'type'=>'SEND_MSG_MOMENT',
            'data' => [
                'ext' => [
                    'content' => '测试发送朋友圈16.44',
                    'images' => [
                        'http://47.105.196.123:8088/uploads/image/20190227/5c76558a96c20.jpg',
                        'http://47.105.196.123:8088/uploads/image/20190227/5c765bbeaa5bd.jpg',
                        'http://47.105.196.123:8088/uploads/image/20190227/5c765c2147d53.jpg'
                    ]
                ],
                'type' => '1'
            ]
        );
        Gateway::sendToAll(  json_encode($new_message));
        $new_message = array(
            'type'=>'SEND_MSG_MOMENT',
            'data' => [
                'ext' => [
                    'content' => '测试纯文字AASsa',
                ],
                'type' => '2'
            ]
        );
        Gateway::sendToAll(  json_encode($new_message));
        $new_message = array(
            'type'=>'SEND_MSG_MOMENT',
            'data' => [
                'ext' => [
                    'url' => 'https://www.baidu.com',
                    'content' => '百度一下，你就知道'
                ],
                'type' => '3'
            ]
        );
        Gateway::sendToAll(  json_encode($new_message));
        $new_message = array(
            'type'=>'SEND_MSG_MOMENT',
            'data' => [
                'ext' => [
                    'url' => 'http://47.105.196.123:8088/5a2f8629d75c096f50cd9ba4aa4d78bc_cps.mp4',
                    'content' => '记录美好生活'
                ],
                'type' => '15'
            ]
        );
        Gateway::sendToAll(  json_encode($new_message));
        // Gateway::sendToClient('7f00000108fd00000001', json_encode($new_message));
    }


    public function friendList()
    {
        $input = Input::only('str','uid','page', 'limit');
        $validator = Validator::make($input, [        
            'str'     =>  'nullable',
            'uid'     => 'required',
            'page'      => 'required',
            'limit'         => 'required',
        ]);
        if ($validator->fails()) {
            return $this->returnError([],401,'参数错误');
        }
        $page = $input['page'];
        $limit = $input['limit'];
        $uid = $input['uid'];
        $weixin = WeixinFriendList::where('weixin_uid',$uid);
        if(isset($input['str'])){
            $weixin->where('alias','like' , '%'.$input['str'].'%')->orwhere('nickname','like' , '%'.$input['str'].'%');
        }
        $count = $weixin->count();
        $data =  $weixin->select('uid as friend_uid','today_talked','alias','nickname','small_head_url','big_head_url')->offset(($page-1)*$limit)
        ->limit($limit)->get();
        $fin['data'] = $data;
        $fin['count'] = $count;
        return $this->returnOk($fin);
    }

    public function chatMessage()
    {
        $input = Input::only('friend_uid','uid','start_at','end_at','str', 'limit','direction','send_time');
        $validator = Validator::make($input, [        
            'friend_uid'     =>  'required',
            'uid'     => 'required',
            'start_at'   => 'nullable',
            'end_at'   => 'nullable',
            'str'   => 'nullable',
            'limit'         => 'required',
            'direction'   => 'nullable',
            'send_time'        => 'nullable',
        ]);
        if ($validator->fails()) {
            return $this->returnError([],401,'参数错误');
        }
        $limit = $input['limit'];
        $uid = $input['uid'];
        $friend_uid = $input['friend_uid'];
        $message = ChatMessage::where('uid',$uid)->where('to_weixin_uid',$friend_uid);
        if(isset($input['str'])){
            $message->where('ext','like' , '%'.$input['str'].'%');
        }
        if(isset($input['start_at'])&&isset($input['end_at'])){
            $message->whereBetween('send_time',[strtotime($input['start_at'] )* 1000,strtotime($input['end_at'])*1000]);
        }
        if(isset($input['direction'])&&isset($input['send_time'])){
            if($input['direction']=='up'){
                $message->where('send_time','<',$input['send_time']);
            }else{
                $message->where('send_time','>',$input['send_time']);
            }
        }
        $count = $message->count();
        $data =  $message->select('uid','to_weixin_uid','msg_type','is_send','status','ext','send_time','msg_id')
            ->orderBy('send_time', 'desc')
            ->limit($limit)
            ->get();
        $friend = WeixinFriendList::where('weixin_uid',$uid)->where('uid',$friend_uid)->first();
        $self = Weixin::where('uid',$uid)->first();
        foreach ($data as $key => $value) {
            unset($data[$key]['to_weixin_uid'],$data[$key]['uid']);
            if($value['is_send']==1){
                $data[$key]['nickname'] = $self['nickname'];
                $data[$key]['uid'] = $self['uid'];
                $data[$key]['small_head_url'] = $self['small_head_url'];
            }else{
                $data[$key]['nickname'] = $friend['nickname'];
                $data[$key]['uid'] = $friend['uid'];
                $data[$key]['small_head_url'] = $friend['small_head_url'];
            }
        }
        if(is_object($data)){
            $data = $data->toArray();
            $data = array_reverse($data);
        }
        $fin['data'] = $data;
        $fin['count'] = $count;
        return $this->returnOk($fin);
    }
}
